﻿@layout DeployLayout

@page "/Deploy/ApplicationInfoList"

@using Materal.APP.Core.Models
@using Deploy.Enums
@using Materal.Common
@using Materal.Model
@using Deploy.DataTransmitModel.ApplicationInfo
@using Deploy.HttpManage
@using Deploy.PresentationModel.ApplicationInfo
@using WebAPP.MateralUI.Models
@using Materal.ConvertHelper
@using WebAPP.Common

@inject MessageManage _messageManage
@inject ExceptionManage _exceptionManage
@inject IApplicationInfoManage _applicationInfoManage

<style>
    .console_message_body {
        height:100%;
    }
</style>

<main class="layout_body">
    <MPageHeader Title="应用程序配置">
        <div class="m_button_group">
            <MButton Disabled="Loading" Class="m_button_icon Micon Micon_plus" Title="新增" ButtonType="@MButtonTypeEnum.Success" OnClick="@OnBtnAddClick"></MButton>
            <MButton Disabled="Loading" Class="m_button_icon Micon Micon_start" Type="全部启动" ButtonType="@MButtonTypeEnum.Primary" OnClick="@OnStartAllClickAsync"></MButton>
            <MButton Disabled="Loading" Class="m_button_icon Micon Micon_stop" Title="全部停止" ButtonType="@MButtonTypeEnum.Danger" OnClick="@OnStopAllClickAsync"></MButton>
        </div>
    </MPageHeader>
    <section class="search_panel">
        <MForm FromData="SearchData" Horizontal>
            <MFormItem Title="名称">
                <MInput Type="search" Disabled="@Loading" @bind-Value="@context.Name"></MInput>
            </MFormItem>
            <MFormItem Title="路径">
                <MInput Type="search" Disabled="@Loading" @bind-Value="@context.Path"></MInput>
            </MFormItem>
            <MFormItem Title="主模块">
                <MInput Type="search" Disabled="@Loading" @bind-Value="@context.MainModule"></MInput>
            </MFormItem>
            <MFormItem Title="类型">
                <MSelect Disabled="@Loading" Items="AllApplicationTypes" @bind-Value="@context.ApplicationType"></MSelect>
            </MFormItem>
            <MFormItem Title="状态">
                <MSelect Disabled="@Loading" Items="AllApplicationStatus" @bind-Value="@context.ApplicationStatus"></MSelect>
            </MFormItem>
            <MFormItem Title="参数">
                <MInput Type="search" Disabled="@Loading" @bind-Value="@context.RunParams"></MInput>
            </MFormItem>
            <MFormItem>
                <MButton Class="m_button_icon Micon Micon_search" Title="查询" Disabled="@Loading" ButtonType="@MButtonTypeEnum.Primary" OnClick="@OnBtnSearchClick"></MButton>
            </MFormItem>
        </MForm>
    </section>
    <MTable DataSource="TableDataSource" TableConfig="TableConfig">
        <MTableCell Width="40">@context.Index</MTableCell>
        <MTableCell Width="150">@context.Name</MTableCell>
        <MTableCell Width="150">@context.Path</MTableCell>
        <MTableCell Width="150">@context.MainModule</MTableCell>
        <MTableCell Width="100">@context.ApplicationTypeString</MTableCell>
        <MTableCell Width="100">@context.ApplicationStatusString</MTableCell>
        <MTableCell>@context.RunParams</MTableCell>
        <MTableCell>
            <div class="m_button_group">
                @switch (context.ApplicationStatus)
                {
                    case ApplicationStatusEnum.Stop:
                        <MButton Class="m_button_icon Micon Micon_edit" Title="修改" OnClick="@(eventArgs => OnBtnEditClick(eventArgs, context.ID))"></MButton>
                        <MButton Class="m_button_icon Micon Micon_start" Title="启动" ButtonType="@MButtonTypeEnum.Primary" OnClick="@(eventArgs => OnStartClickAsync(eventArgs, context.ID))"></MButton>
                        <MButton Class="m_button_icon Micon Micon_delete" Title="删除" ButtonType="@MButtonTypeEnum.Danger" OnClick="@(eventArgs => OnBtnOpenDeleteModalClick(eventArgs, context.ID))"></MButton>
                        break;
                    case ApplicationStatusEnum.Runing:
                        <MButton Class="m_button_icon Micon Micon_console" Title="控制台" OnClick="@(eventArgs => OnConsoleMessageClickAsync(eventArgs, context.ID))"></MButton>
                        <MButton Class="m_button_icon Micon Micon_stop" Title="停止" ButtonType="@MButtonTypeEnum.Danger" OnClick="@(eventArgs => OnStopClickAsync(eventArgs, context.ID))"></MButton>
                        break;
                }
            </div>
        </MTableCell>
    </MTable>
</main>
<MModal Title="@(SelectedUserID.HasValue ? "修改" : "新增")" Width="900" ModalType="@MModalTypeEnum.Large" @bind-Display="OperationModalDisplay">
    <OperationApplicationInfo ApplicationInfoID="SelectedUserID" Success="@OnOperationSuccessAsync" Cancel="@CloseOperationModal"></OperationApplicationInfo>
</MModal>
<MModal Title="删除" @bind-Display="DeleteModalDisplay">
    确定要删除该项吗？
    <div class="m_modal_buttons">
        <MButton Disabled="@Loading" OnClick="@CloseDeleteModal">取消</MButton>
        <MButton ButtonType="@MButtonTypeEnum.Danger" Disabled="@Loading" OnClick="@OnBtnDeleteClickAsync">删除</MButton>
    </div>
</MModal>
<MModal Title="控制台" ModalType="MModalTypeEnum.Large" @bind-Display="ConsoleModalDisplay">
    <div class="console_message_body">
        @foreach (string message in ConsoleMessages)
        {
            <p>@message</p>
        }
    </div>
    <div class="m_modal_buttons">
        <MButton OnClick="@CloseConsoleModal">关闭</MButton>
    </div>
</MModal>
@code{
    /// <summary>
    /// 查询数据模型
    /// </summary>
    public class ApplicationInfoSearchFromDataModel
    {
        /// <summary>
        /// 查询应用程序类型
        /// </summary>
        public KeyValueModel ApplicationType { get; set; } = new KeyValueModel(null, "所有类型");
        /// <summary>
        /// 查询应用程序状态
        /// </summary>
        public KeyValueModel ApplicationStatus { get; set; } = new KeyValueModel(null, "所有状态");
        /// <summary>
        /// 名称
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// 路径
        /// </summary>
        public string Path { get; set; }
        /// <summary>
        /// 主模块
        /// </summary>
        public string MainModule { get; set; }
        /// <summary>
        /// 运行参数
        /// </summary>
        public string RunParams { get; set; }
    }
    /// <summary>
    /// 应用程序信息列表模型
    /// </summary>
    public class ApplicationInfoListModel : ApplicationInfoListDTO
    {
        public ApplicationInfoListModel()
        {

        }
        public ApplicationInfoListModel(ApplicationInfoListDTO listDTO, int index)
        {
            listDTO.CopyProperties(this);
            Index = index + 1;
        }
        /// <summary>
        /// 位序
        /// </summary>
        public int Index { get; set; }
    }
}
@code{
    #region 属性
    /// <summary>
    /// 选中的用户唯一标识
    /// </summary>
    public Guid? SelectedUserID { get; set; }
    /// <summary>
    /// 操作模态窗是否显示
    /// </summary>
    public bool OperationModalDisplay { get; set; }
    /// <summary>
    /// 删除模态窗是否显示
    /// </summary>
    public bool DeleteModalDisplay { get; set; }
    /// <summary>
    /// 控制台模态窗是否显示
    /// </summary>
    public bool ConsoleModalDisplay { get; set; }
    /// <summary>
    /// 所有应用程序类型
    /// </summary>
    public List<KeyValueModel> AllApplicationTypes { get; set; }
    /// <summary>
    /// 所有应用程序状态
    /// </summary>
    public List<KeyValueModel> AllApplicationStatus { get; set; }
    /// <summary>
    /// 查询数据
    /// </summary>
    public ApplicationInfoSearchFromDataModel SearchData { get; set; } = new ApplicationInfoSearchFromDataModel();
    /// <summary>
    /// 加载中
    /// </summary>
    public bool Loading { get; set; } = true;
    /// <summary>
    /// 表格配置
    /// </summary>
    public List<TableConfigModel> TableConfig { get; set; }
    /// <summary>
    /// 表格数据源
    /// </summary>
    public List<ApplicationInfoListModel> TableDataSource { get; set; }
    /// <summary>
    /// 控制台消息
    /// </summary>
    public ICollection<string> ConsoleMessages { get; set; }
    #endregion
    #region 生命周期
    /// <summary>
    /// 设置参数后
    /// </summary>
    /// <returns></returns>
    protected override async Task OnParametersSetAsync()
    {
        AllApplicationTypes = KeyValueModel.GetAllCode(typeof(ApplicationTypeEnum));
        AllApplicationTypes.Insert(0, SearchData.ApplicationType);
        AllApplicationStatus = KeyValueModel.GetAllCode(typeof(ApplicationStatusEnum));
        AllApplicationStatus.Insert(0, SearchData.ApplicationStatus);
        TableConfig = new List<TableConfigModel>
        {
            new TableConfigModel("#"),
            new TableConfigModel("名称"),
            new TableConfigModel("路径"),
            new TableConfigModel("主模块"),
            new TableConfigModel("应用类型"),
            new TableConfigModel("应用状态"),
            new TableConfigModel("运行参数"),
            new TableConfigModel("操作")
        };
        TableDataSource = new List<ApplicationInfoListModel>();
        await base.OnParametersSetAsync();
    }
    /// <summary>
    /// 页面呈现后
    /// </summary>
    /// <param name="firstRender"></param>
    /// <returns></returns>
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (!firstRender) return;
        await SearchTableDataAsync();
        await base.OnAfterRenderAsync(true);
        StateHasChanged();
    }
    #endregion
    #region 事件
    /// <summary>
    /// 单击新增按钮
    /// </summary>
    /// <param name="eventArgs"></param>
    /// <returns></returns>
    public void OnBtnAddClick(MouseEventArgs eventArgs)
    {
        SelectedUserID = null;
        OpenOperationModal();
    }
    /// <summary>
    /// 单击修改按钮
    /// </summary>
    /// <param name="eventArgs"></param>
    /// <param name="selectedID"></param>
    /// <returns></returns>
    public void OnBtnEditClick(MouseEventArgs eventArgs, Guid selectedID)
    {
        SelectedUserID = selectedID;
        OpenOperationModal();
    }
    /// <summary>
    /// 单击删除按钮
    /// </summary>
    /// <param name="eventArgs"></param>
    /// <param name="selectedID"></param>
    /// <returns></returns>
    public void OnBtnOpenDeleteModalClick(MouseEventArgs eventArgs, Guid selectedID)
    {
        SelectedUserID = selectedID;
        OpenDeleteModal();
    }
    /// <summary>
    /// 单击删除按钮
    /// </summary>
    /// <param name="eventArgs"></param>
    /// <returns></returns>
    public async Task OnBtnDeleteClickAsync(MouseEventArgs eventArgs)
    {
        await DeleteAsync();
    }
    /// <summary>
    /// 单击查询按钮
    /// </summary>
    /// <param name="eventArgs"></param>
    /// <returns></returns>
    public async Task OnBtnSearchClick(MouseEventArgs eventArgs)
    {
        await SearchTableDataAsync();
    }
    /// <summary>
    /// 当前页发生更新
    /// </summary>
    /// <returns></returns>
    public async Task OnPageIndexChangedAsync()
    {
        await SearchTableDataAsync();
    }
    /// <summary>
    /// 修改成功
    /// </summary>
    /// <returns></returns>
    public async Task OnOperationSuccessAsync()
    {
        await SearchTableDataAsync();
        CloseOperationModal();
    }
    /// <summary>
    /// 单击启动全部
    /// </summary>
    /// <param name="eventArgs"></param>
    public async Task OnStartAllClickAsync(MouseEventArgs eventArgs)
    {
        await StartAllAsync();
    }
    /// <summary>
    /// 单击启动全部
    /// </summary>
    /// <param name="eventArgs"></param>
    public async Task OnStopAllClickAsync(MouseEventArgs eventArgs)
    {
        await StopAllAsync();
    }
    /// <summary>
    /// 单击启动
    /// </summary>
    /// <param name="eventArgs"></param>
    /// <param name="selectedID"></param>
    public async Task OnStartClickAsync(MouseEventArgs eventArgs, Guid selectedID)
    {
        await StartAsync(selectedID);
    }
    /// <summary>
    /// 单击停止
    /// </summary>
    /// <param name="eventArgs"></param>
    /// <param name="selectedID"></param>
    public async Task OnStopClickAsync(MouseEventArgs eventArgs, Guid selectedID)
    {
        await StopAsync(selectedID);
    }
    /// <summary>
    /// 单击获得控制台消息
    /// </summary>
    /// <param name="eventArgs"></param>
    /// <param name="selectedID"></param>
    public async Task OnConsoleMessageClickAsync(MouseEventArgs eventArgs, Guid selectedID)
    {
        await ShowConsoleMessageAsync(selectedID);
    }
    #endregion
    #region 私有方法
    /// <summary>
    /// 打开操作模态框
    /// </summary>
    private void OpenOperationModal()
    {
        OperationModalDisplay = true;
    }
    /// <summary>
    /// 关闭删除操作模态框
    /// </summary>
    private void CloseOperationModal()
    {
        OperationModalDisplay = false;
    }
    /// <summary>
    /// 打开删除模态框
    /// </summary>
    private void OpenDeleteModal()
    {
        DeleteModalDisplay = true;
    }
    /// <summary>
    /// 关闭删除模态框
    /// </summary>
    private void CloseDeleteModal()
    {
        DeleteModalDisplay = false;
    }
    /// <summary>
    /// 查询表格数据
    /// </summary>
    /// <returns></returns>
    private async Task SearchTableDataAsync()
    {
        Loading = true;
        try
        {
            var requestModel = new QueryApplicationInfoFilterRequestModel
            {
                Name = SearchData.Name,
                MainModule = SearchData.MainModule,
                Path = SearchData.Path,
                RunParams = SearchData.RunParams
            };
            if (SearchData.ApplicationType.Key == null)
            {
                requestModel.ApplicationType = null;
            }
            else
            {
                requestModel.ApplicationType = (ApplicationTypeEnum)Convert.ToInt32(SearchData.ApplicationType.Key);
            }
            if (SearchData.ApplicationStatus.Key == null)
            {
                requestModel.ApplicationStatus = null;
            }
            else
            {
                requestModel.ApplicationStatus = (ApplicationStatusEnum)Convert.ToInt32(SearchData.ApplicationStatus.Key);
            }
            ResultModel<List<ApplicationInfoListDTO>> resultModel = await _applicationInfoManage.GetListAsync(requestModel);
            if (resultModel.ResultType == ResultTypeEnum.Success)
            {
                TableDataSource.Clear();
                ApplicationInfoListDTO[] dataListDto = resultModel.Data.ToArray();
                for (var i = 0; i < dataListDto.Length; i++)
                {
                    TableDataSource.Add(new ApplicationInfoListModel(dataListDto[i], i));
                }
            }
            else
            {
                await _messageManage.WarningAsync(resultModel.Message);
            }
        }
        catch (Exception exception)
        {
            await _exceptionManage.HandlerExceptionAsync(exception);
        }
        finally
        {
            Loading = false;
        }
    }
    /// <summary>
    /// 删除
    /// </summary>
    /// <returns></returns>
    private async Task DeleteAsync()
    {
        Loading = true;
        try
        {
            if (!SelectedUserID.HasValue) throw new WebAPPException("未选择数据");
            ResultModel resultModel = await _applicationInfoManage.DeleteAsync(SelectedUserID.Value);
            if (resultModel.ResultType == ResultTypeEnum.Success)
            {
                await _messageManage.SuccessAsync(resultModel.Message);
                await SearchTableDataAsync();
                CloseDeleteModal();
            }
            else
            {
                await _messageManage.WarningAsync(resultModel.Message);
            }
        }
        catch (Exception exception)
        {
            await _exceptionManage.HandlerExceptionAsync(exception);
        }
        finally
        {
            Loading = false;
        }
    }
    /// <summary>
    /// 启动所有
    /// </summary>
    /// <returns></returns>
    private async Task StartAllAsync()
    {
        Loading = true;
        try
        {
            ResultModel resultModel = await _applicationInfoManage.StartAllAsync();
            if (resultModel.ResultType == ResultTypeEnum.Success)
            {
                await _messageManage.SuccessAsync(resultModel.Message);
                await SearchTableDataAsync();
            }
            else
            {
                await _messageManage.WarningAsync(resultModel.Message);
            }
        }
        catch (Exception exception)
        {
            await _exceptionManage.HandlerExceptionAsync(exception);
        }
        finally
        {
            Loading = false;
        }
    }
    /// <summary>
    /// 停止所有
    /// </summary>
    /// <returns></returns>
    private async Task StopAllAsync()
    {
        Loading = true;
        try
        {
            ResultModel resultModel = await _applicationInfoManage.StopAllAsync();
            if (resultModel.ResultType == ResultTypeEnum.Success)
            {
                await _messageManage.SuccessAsync(resultModel.Message);
                await SearchTableDataAsync();
            }
            else
            {
                await _messageManage.WarningAsync(resultModel.Message);
            }
        }
        catch (Exception exception)
        {
            await _exceptionManage.HandlerExceptionAsync(exception);
        }
        finally
        {
            Loading = false;
        }
    }
    /// <summary>
    /// 启动
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    private async Task StartAsync(Guid id)
    {
        Loading = true;
        try
        {
            ResultModel resultModel = await _applicationInfoManage.StartAsync(id);
            if (resultModel.ResultType == ResultTypeEnum.Success)
            {
                await _messageManage.SuccessAsync(resultModel.Message);
                await SearchTableDataAsync();
            }
            else
            {
                await _messageManage.WarningAsync(resultModel.Message);
            }
        }
        catch (Exception exception)
        {
            await _exceptionManage.HandlerExceptionAsync(exception);
        }
        finally
        {
            Loading = false;
        }
    }
    /// <summary>
    /// 停止
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    private async Task StopAsync(Guid id)
    {
        Loading = true;
        try
        {
            ResultModel resultModel = await _applicationInfoManage.StopAsync(id);
            if (resultModel.ResultType == ResultTypeEnum.Success)
            {
                await _messageManage.SuccessAsync(resultModel.Message);
                await SearchTableDataAsync();
            }
            else
            {
                await _messageManage.WarningAsync(resultModel.Message);
            }
        }
        catch (Exception exception)
        {
            await _exceptionManage.HandlerExceptionAsync(exception);
        }
        finally
        {
            Loading = false;
        }
    }
    /// <summary>
    /// 停止
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    private async Task ShowConsoleMessageAsync(Guid id)
    {
        Loading = true;
        try
        {
            ResultModel<ICollection<string>> resultModel = await _applicationInfoManage.GetConsoleMessageAsync(id);
            if (resultModel.ResultType == ResultTypeEnum.Success)
            {
                ConsoleMessages = resultModel.Data;
                OpenConsoleModal();
            }
            else
            {
                await _messageManage.WarningAsync(resultModel.Message);
            }
        }
        catch (Exception exception)
        {
            await _exceptionManage.HandlerExceptionAsync(exception);
        }
        finally
        {
            Loading = false;
        }
    }
    /// <summary>
    /// 打开删除模态框
    /// </summary>
    private void OpenConsoleModal()
    {
        ConsoleModalDisplay = true;
    }
    /// <summary>
    /// 关闭删除模态框
    /// </summary>
    private void CloseConsoleModal()
    {
        ConsoleModalDisplay = false;
    }
    #endregion
}